package com.usa.tool;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author YueGod
 * @since 2023/12/25
 */
@SpringBootTest(classes = App.class)
public class CleanRedisKey {

    private static final String KEY = "mq_message_status_*";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Test
    public void clean() {
        List<String> keys = findKeysWithNoExpiration();
        while (!keys.isEmpty()) {
            stringRedisTemplate.delete(keys);
            keys = findKeysWithNoExpiration();
        }

    }

    public List<String> findKeysWithNoExpiration() {
        List<String> keys = new ArrayList<>();
        Map<String, Long> keyExpireMap = new HashMap<>();
        try (RedisConnection connection = stringRedisTemplate.getConnectionFactory().getConnection()) {
            // 使用scan命令查找所有匹配的key
            Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().match("mq_message_status_*").count(10000).build());
            while (cursor.hasNext()) {
                String key = new String(cursor.next());
                keys.add(key);
            }
            System.out.println(keys.size());
            // 使用pipeline批量获取key的过期时间
            connection.openPipeline();
            keys.forEach(key -> connection.pTtl(key.getBytes()));
            List<Object> expireTimes = connection.closePipeline();

            // 将key和其对应的过期时间放入Map
            for (int i = 0; i < keys.size(); i++) {
                keyExpireMap.put(keys.get(i), (Long) expireTimes.get(i));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 过滤出过期时间为-1的key
        List<String> keysWithNoExpire = new ArrayList<>();
        for (Map.Entry<String, Long> entry : keyExpireMap.entrySet()) {
            if (entry.getValue().equals(-1L)) {
                keysWithNoExpire.add(entry.getKey());
            }
        }

        return keysWithNoExpire;
    }
}



